/**
 *  timer.cpp
 *  AwkwardCubed - Sys
 *
 *  Date: 21/08/2013
 *
 *  Language: C++
 *
 *  @author Carl mcCaffrey
 *
 */
#include "sys/timer.h"

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <Windows.h>

void Timer::Init(void)
{
	secondsPerCount = 0.0;
	timeDelta = 0;
	baseTime = 0;
	pausedTime = 0;
	prevTime = 0;
	currentTime = 0;
	stopped = false;

	int64 countsPerSec;
	QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
	secondsPerCount = 1.0 / (double)countsPerSec;
}

float Timer::TotalTime(void)
{
	if(stopped){
		return (float)(((stopTime - pausedTime) - baseTime) * secondsPerCount);
	}else{
		return (float)(((currentTime - pausedTime) - baseTime) * secondsPerCount);
	}
}

float Timer::DeltaTime(void)
{
	return (float)timeDelta;
}

void Timer::Reset(void)
{
	int64 currTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&currTime);

	baseTime = currTime;
	prevTime = currTime;
	stopTime = 0;
	stopped = false;
}

void Timer::Start(void)
{
	int64 startTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&startTime);

	if(stopped){
		pausedTime += (startTime - stopTime);
		prevTime = startTime;
		stopTime = 0;
		stopped = false;
	}
}

void Timer::Stop(void)
{
	if(!stopped){
		int64 currTime;
		QueryPerformanceCounter((LARGE_INTEGER*)&currTime);

		stopTime = currTime;
		stopped =  true;
	}
}

void Timer::Tick(void)
{
	if(stopped){
		timeDelta = 0.0;
		return;
	}

	int64 currTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
	currentTime = currTime;

	timeDelta = (currentTime - prevTime) * secondsPerCount;

	prevTime = currentTime;

	if(timeDelta < 0.0f){
		timeDelta = 0.0f;
	}
}